﻿/*
* Copyright 2010 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Criterion;
using Ngilead.Test.Models;
using System.Collections;

namespace Ngilead.Test.DAO
{
    /// <summary>
    /// Generic DAO class
    /// </summary>
    public class GenericDAO<TModel, TId> where TModel : IModel
    {
        #region Session

        /// <summary>
        /// Get session
        /// </summary>
        /// <returns>Session</returns>
        protected ISession GetSession()
        {
            return NhibernateContext.GetSession();
        }

        #endregion

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <param name="id">Id</param>
        /// <returns>Object</returns>
        public TModel LoadById(TId id)
        {
            TModel result = default(TModel);
            ISession session = null;
            ITransaction transaction = null;

            try
            {
                session = GetSession();
                transaction = session.BeginTransaction();
                result = (TModel)session.Get(typeof(TModel), id);
                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                throw new Exception(String.Format("Could not get {0} for id {1}", typeof(TModel).Name, id), ex);
            }

            return result;
        }

        /// <summary>
        /// Load all objects by id
        /// </summary>
        /// <returns>All objects</returns>
        public IList<TModel> LoadAll()
        {
            IList<TModel> result = null;

            try
            {
                result = LoadByCriteria();
            }
            catch (Exception ex)
            {
                throw new Exception(String.Format("Could not get all {0}", typeof(TModel).Name), ex);
            }

            return result;
        }

        /// <summary>
        /// Load by criteria
        /// </summary>
        /// <param name="criterion">Criteria</param>
        /// <returns>Objects</returns>
        protected IList<TModel> LoadByCriteria(params ICriterion[] criterion)
        {
            IList<TModel> result = null;
            ISession session = null;
            ITransaction transaction = null;

            try
            {
                session = GetSession();
                transaction = session.BeginTransaction();
                ICriteria criteria = session.CreateCriteria(typeof(TModel));
                foreach (ICriterion c in criterion)
                {
                    criteria.Add(c);
                }
                result = criteria.List<TModel>();
                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                throw new Exception(String.Format("Could not get {0} by criteria", typeof(TModel).Name), ex);
            }

            return result;
        }

        /// <summary>
        /// Count all objects
        /// </summary>
        /// <returns>Count</returns>
        public Int64 CountAll()
        {
            Int64 count = 0;
            ISession session = null;
            ITransaction transaction = null;

            try
            {
                session = GetSession();
                transaction = session.BeginTransaction();
                count = session.CreateQuery(String.Concat("SELECT COUNT(*) FROM ", typeof(TModel).Name)).UniqueResult<Int64>();
                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                throw new Exception(String.Format("Could not count {0}", typeof(TModel).Name), ex);
            }

            return count;
        }

        /// <summary>
        /// Save or update object
        /// </summary>
        /// <param name="obj">Object</param>
        public void Save(TModel obj)
        {
            ISession session = null;
            ITransaction transaction = null;

            try
            {
                session = GetSession();
                transaction = session.BeginTransaction();
                session.SaveOrUpdate(obj);
                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                throw new Exception(String.Format("Could not save {0} {1}", obj.GetType().Name, obj.ToString()), ex);
            }
        }

        /// <summary>
        /// Delete object
        /// </summary>
        /// <param name="obj">Object</param>
        public void Delete(TModel obj)
        {
            ISession session = null;
            ITransaction transaction = null;

            try
            {
                session = GetSession();
                transaction = session.BeginTransaction();
                session.Delete(obj);
                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                throw new Exception(String.Format("Could not delete {0} {1}", obj.GetType().Name, obj.ToString()), ex);
            }
        }
    }
}
